use super::Entry;
use std::io::Read;
use std::path::Path;
use std::fs::{self, File};
use std::error::Error;
use std::fmt;

#[derive(Debug)]
pub struct DirEntry {
    abs_dir: String
}

impl DirEntry {
    pub fn new(path: &str) -> DirEntry {
        let path = Path::new(path);
        match fs::canonicalize(path) {
            Ok(abs_path) => DirEntry{ 
                abs_dir: abs_path.to_str().unwrap().to_string() 
            },
            Err(e) => panic!("{e}")
        }
    }
}

impl Entry for DirEntry {
    fn read_class(&self, class_name: &str) -> Result<Vec<u8>, Box<dyn Error>> {
        // 拼接路径与文件名
        let filename = Path::new(&self.abs_dir).join(class_name);
        // 获取文件
        let mut file = File::open(filename)?;
        // 数据
        let mut data = vec![];
        file.read_to_end(&mut data)?;
        Ok(data)
    }

    fn string(&self) -> String {
        self.abs_dir.clone()
    }
}

impl fmt::Display for DirEntry {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.string())
    }
}